package smashedapples.events
{
	import flash.events.EventDispatcher;
	
	import mx.rpc.AsyncToken;
	import mx.rpc.IResponder;
	
	
	[Event( name="chainComplete", type="smashedapples.events.AsyncChainEvent" )]
	
	public class AsyncEventChainResponder extends EventDispatcher implements IResponder
	{
		
		public var tokens:Array = [];
		
		public var returned:Array = [];
		
		public function AsyncEventChainResponder( tokens:Array = null, asyncEventChainResponders:Array = null )
		{
			if( tokens != null )
				this.addTokens( tokens );
				
			if( asyncEventChainResponders != null )
				this.addResponders( asyncEventChainResponders );
		}
		
		
		public function addResponders( responders:Array ):void
		{
			for each( var responder:IAsyncChainResponder in responders )
			{
				this.addEventListener( AsyncChainEvent.CHAIN_COMPLETE, responder.handleAsyncChainComplete );
			}	
		}
		
		public function addTokens( tokens:Array ):void
		{
			for each( var token:AsyncToken in tokens )
			{
				token.addResponder( this );
			}
			
			this.tokens = tokens;
		}
	
		public function result( event:Object ):void
		{
			this.markEventAsReturned( event );
		}
		
		public function fault( event:Object ):void
		{
			this.markEventAsReturned( event );
		}
		
		private function markEventAsReturned( event:Object ):void
		{
			this.returned.push( event );
			
			if( returned.length == tokens.length)
				dispatchEvent( new AsyncChainEvent( this.returned ) );
			
		}
		
		
	}
}